package org.example.struct.array;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liyishan
 * @date 2023/8/22 09:58
 * @apiNote
 */

public class Test01122RelativeSortArray {
    public static void main(String[] args) {
        int[] arr1 = {2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19};
        int[] arr2 = {2, 1, 4, 3, 9, 6};
        int[] res = test(arr1, arr2);
        System.out.println(JSON.toJSON(res));
    }

    public static int[] test(int[] arr1, int[] arr2) {
        int n = arr1.length;
        int m = arr2.length;
        Map<Integer, Integer> map = new HashMap<>();
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            map.put(arr1[i], map.getOrDefault(arr1[i], 0) + 1);
        }
        int size = 0;
        for (int i = 0; i < m; i++) {
            int len = map.get(arr2[i]);
            int j = 0;
            while (j < len) {
                res[size++] = arr2[i];
                j++;
            }
            map.remove(arr2[i]);
        }
        int x = n-size;
        int[] temp = new int[x];
        int l = 0;
        for(Map.Entry<Integer,Integer> entry:map.entrySet()){
            int key = entry.getKey();
            int value =entry.getValue();
            int y=0;
            while(y<value){
                temp[l++] = key;
                y++;
            }
        }
        Arrays.sort(temp);
        for(int i = size ;i<n;i++){
            res[i] = temp[i-size];
        }
        return res;
    }
}
